#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Filename: case_number.py
# Author: ChenChangSong
# Date: 2025-08-24
"""
功能描述: 获取测试用例数量
https://open.tapd.cn/document/api-doc/API%E6%96%87%E6%A1%A3/api_reference/tcase/get_tcase_categories_count.html
"""

from comm.common_code import *


def tcases_get_count(dir_id='', max_retries=5):
    """获取用例数量（注意：不会获取递归目录的）
    :param dir_id: 用例目录ID
    :param max_retries: 最大重试次数（针对429限流）
    """
    excel_data = get_excel_data()
    url = f"https://api.tapd.cn/tcases/count"
    payload = {
        "access_token": excel_data['access_token'], 
        "category_id": dir_id,  # 用例目录ID
        "workspace_id": excel_data['项目ID'],  # 项目ID
    }
    
    retries = 0
    while retries <= max_retries:
        logger.info(f'获取用例目录{dir_id}下的用例数量↓↓↓=================================================↓↓↓')
        response_code, response = api_request(method="GET", url=url, headers={}, params=payload)
        
        if response_code == 429:  # 限流错误
            retries += 1
            if retries > max_retries:
                logger.error(f"达到最大重试次数({max_retries})，仍然被限流")
                return response_code, response
                
            # 计算等待时间（指数退避）
            wait_time = 2 ** retries
            logger.warning(f"遇到限流，等待{wait_time}秒后重试 ({retries}/{max_retries})")
            time.sleep(wait_time)
            continue
            
        logger.info(f"响应内容: {response}")
        logger.info(f'↑↑↑=================================================↑↑↑')
        return response_code, response

if __name__ == "__main__":
    tcases_get_count(dir_id='1166606973001003058')
